package com.tccmeta.matchmaker.controller;

import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.net.URLEncoder;

/**
 * @Author:xiaoyu
 * @Created on 2018/9/17
 * @Description 公众号网页授权登录
 */
@Controller
@RequestMapping(value = "/webAuthorized")
@Slf4j
public class UserWebAuthorizedController {

    @Resource
    WxMpService wxMpService;

    /**
     * s微信网页授权
     */
    @GetMapping("/authorize")
    public String welcome() {
        //授权成功后跳转同域名下的网页
        String returnUrl = "host";
        //重定向的回调链接地址
        String url = "host" + "/wechat_alipay_tool/webAuthorized/oauth2";
        String redirectUrl = wxMpService.oauth2buildAuthorizationUrl(url, WxConsts.OAuth2Scope.SNSAPI_USERINFO, URLEncoder.encode(returnUrl));
        return "redirect:" + redirectUrl;
    }

    /**
     * 授权获取用户信息
     *
     * @param code
     * @return
     */
    @GetMapping("/oauth2")
    public ResponseEntity oauth2(@RequestParam(name = "code") String code) throws WxErrorException {
        WxMpOAuth2AccessToken accessToken = wxMpService.oauth2getAccessToken(code);
        WxMpUser wxMpUser = wxMpService.oauth2getUserInfo(accessToken, "zh_CN");
        log.info("用户信息:{}", wxMpUser);
        return ResponseEntity.ok(wxMpUser);
    }

}
